﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using ScaleDataInterpreter;
using Brushes = System.Windows.Media.Brushes;

namespace weighing
{
    /// <summary>
    /// ScaleItem.xaml 的交互逻辑
    /// </summary>
    public partial class ScaleItem : System.Windows.Controls.UserControl
    {

        #region  variables
        private Style? NomalStyle;
        private Style? ErrorStyle;
        public ScaleVo? mVo; 
        /// <summary>
        /// 读取磅称时间间隔 ms
        /// </summary>
        private readonly int ReadSerialPortDataPeriod = 1000;
        #endregion


        public ScaleItem()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            this.NomalStyle = FindResource("nomalEllipseStyle") as Style;
            this.ErrorStyle = FindResource("errorEllipseStyle") as Style;

            this.DataContextChanged += ScaleItem_DataContextChanged;

            UpdateUnitText();
        }
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            mVo?.DisposeSerialPort();
        }
        private void ScaleItem_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.DataContext is ScaleVo vo)
            {
                mVo = vo;
                if (vo.DefaultType != null)
                {
                    this.DefaultBy = (WeightingBillType)vo.DefaultType;
                }
                if (this.DefaultBy == WeightingBillType.Buy)
                {
                    this.RootCard.ToolTip = "默认为入库";
                }
                else if (this.DefaultBy == WeightingBillType.Sale)
                {
                    this.RootCard.ToolTip = "默认为出库";
                }
                else
                {
                    this.RootCard.ToolTip = "未设置认为入库或出库";
                }
                if (mVo.Status == 1)
                {
                    this.statusEllipse.Style = this.NomalStyle;
                }
                else
                {
                    this.statusEllipse.Style = this.ErrorStyle;
                }

                if (mVo != null)
                {
                    if (mVo.IsVirtual)
                    {
                        // virtual

                    }
                    else
                    {
                        //local 
                        vo.DisposeSerialPort();
                        try
                        {
                            vo.SerialPort.Open();
                            string msg = $"{vo.Name}的端口{vo.Com} 打开成功！";                    
                            mVo.DisposeTimer();
                            mVo.Timer = new System.Threading.Timer(SerialPortCallBack, mVo, 400, ReadSerialPortDataPeriod);
                        }
                        catch (Exception er)
                        {
                            string msg = $"{vo.Name}的端口{vo.Com} 打开失败！波特率为：{vo.BaudRate}。错误信息：{er.Message}";
                            Console.WriteLine(msg);                          
                            mVo.Info = msg;
                        }
                    }

                }
                else
                {
                    Console.WriteLine("磅称判定的对你像为空");
                }
            }
        }

        #region dependProperty

        public WeightingBillType DefaultBy
        {
            get { return (WeightingBillType)GetValue(DefaultByProperty); }
            set { SetValue(DefaultByProperty, value); }
        }

        public static readonly DependencyProperty DefaultByProperty =
            DependencyProperty.Register("DefaultBy", typeof(WeightingBillType), typeof(ScaleItem), new PropertyMetadata(WeightingBillType.Buy));

        public Boolean IsSelected
        {
            get { return (Boolean)GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        public static readonly DependencyProperty IsSelectedProperty =
            DependencyProperty.Register("IsSelected", typeof(Boolean), typeof(ScaleItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsMeasure, OnIsSelectedChanged));

        public static void OnIsSelectedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ScaleItem item = sender as ScaleItem;
            SelectItem(item, (bool)e.NewValue);
        }

        public static void SelectItem(ScaleItem item, bool isSelected = true)
        {
            if (isSelected == true)
            {
                if (item.mVo is ScaleVo)
                {
                    if (item.mVo != null && item.mVo.Status == 1)
                    {
                        item.statusEllipse.Style = item.NomalStyle;
                        item.RootCard.BorderBrush = Brushes.Blue;
                        item.RootCard.Foreground = Brushes.Black;
                        item.RootCard.Background = Brushes.LightBlue;
                    }
                    else if (item.mVo != null && item.mVo.Status == 0)
                    {
                        item.statusEllipse.Style = item.ErrorStyle;
                        item.RootCard.BorderBrush = Brushes.Red;
                        item.RootCard.Foreground = Brushes.Red;
                        item.RootCard.BorderBrush = Brushes.OrangeRed;
                        item.RootCard.Background = Brushes.White;
                    }
                    else { }
                }
            }
            else
            {
                item.RootCard.BorderBrush = Brushes.LightGray;
                item.RootCard.Foreground = Brushes.Black;
                item.RootCard.Background = Brushes.White;
            }
        }
        #endregion

        private void RootCard_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            bool isSelf = false;
            foreach (var item in App.scaleItems)
            {
                if (mVo == item.DataContext)
                {
                    isSelf = true;
                    continue;
                }
                item.IsSelected = false;
            }
            if (isSelf == false)
            {
                this.IsSelected = true;
            }
            else
            {
                this.IsSelected = !this.IsSelected;
            }
        }

        /// <summary>
        /// 显示数据 回调
        /// </summary>
        /// <param name="stae"></param>
        private void SerialPortCallBack(Object scaleVo)
        {
            if (scaleVo is ScaleVo vo)
            {
                ScaleDataResult result = vo.Interpreter.ReadValue();
                if (result.ErrCode == 0)
                {
                    this.Dispatcher.Invoke(
                        new Action(delegate
                        {
                            vo.Tonner = App.Config.WeighingConfig.Unit == Unit.KG ?
                                        Math.Round(result.Value, App.Config.WeighingConfig.Digits, MidpointRounding.AwayFromZero) :
                                        Math.Round(result.Value / 1000, App.Config.WeighingConfig.Digits, MidpointRounding.AwayFromZero);
                            vo.Info = result.Msg;
                            vo.Status = 1;
                            ChangeViswStatus(1, vo.IsSelected);                                                     
                        }));


                }
                else
                {
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        vo.Tonner = 0;
                        vo.Info = result.Msg;
                        vo.Status = 0;
                        string msg = $"{vo.Name} 的端口{vo.Com} 读取数据出错！错误信息：{result.Msg}";
                       
                        ChangeViswStatus(0, vo.IsSelected);

                    }));
                }
            }
            else
            {
                string msg = $"读取数据出错！错误信息：数据参数不是一个ScaleVo 对像的实例";
                Growl.InfoGlobal(msg);                
            }
        }

        private void ChangeViswStatus(int status, bool isSelect)
        {
            if (status == 1)
            {
                if (IsSelected)
                {
                    if (RootCard.BorderBrush != Brushes.Blue)
                    {
                        statusEllipse.Style = NomalStyle;
                        RootCard.BorderBrush = Brushes.Blue;
                        RootCard.Foreground = Brushes.Black;
                        RootCard.Background = Brushes.LightBlue;
                    }
                }
                else
                {
                    if (RootCard.BorderBrush != Brushes.LightGray)
                    {
                        statusEllipse.Style = NomalStyle;
                        RootCard.BorderBrush = Brushes.LightGray;
                        RootCard.Foreground = Brushes.Black;
                        RootCard.Background = Brushes.White;
                    }
                }
            }
            else
            {
                if (IsSelected)
                {
                    if (RootCard.BorderBrush != Brushes.Red)
                    {
                        statusEllipse.Style = ErrorStyle;
                        RootCard.BorderBrush = Brushes.Red;
                        RootCard.Foreground = Brushes.Red;
                        RootCard.Background = Brushes.White;
                    }
                }
                else
                {
                    if (RootCard.BorderBrush != Brushes.LightGray)
                    {
                        statusEllipse.Style = NomalStyle;
                        RootCard.BorderBrush = Brushes.LightGray;
                        RootCard.Foreground = Brushes.LightGray;
                        RootCard.Background = Brushes.White;
                    }
                }
            }
        }

        //更新称重单位
        public void UpdateUnitText()
        {
            //"吨" : "千克";
            string t = App.Config.WeighingConfig.Unit == Unit.Tone ? LangHelper.Get(LangKeyNames.UnitTone) : LangHelper.Get(LangKeyNames.UnitKg);
            this.unitTb.Text = t;
        }




        //you code end
    }
}
